//
//  MZBaseWebViewController.m
//  MagicXinBusiness
//
//  Created by 陳烁 on 2017/9/6.
//
//

#import "MZBaseWebViewController.h"
#import <WebKit/WebKit.h>
#import "Masonry.h"
#import "BlocksKit.h"
#import "BlocksKit+UIKit.h"

@interface MZBaseWebViewController () <WKScriptMessageHandler,WKUIDelegate,WKNavigationDelegate>

@property (nonatomic) WKWebView *webView;
@property (nonatomic) UIProgressView *progressView;
@property (nonatomic,copy) NSString *urlString;

@end

#define MyScreenWidth [UIScreen mainScreen].bounds.size.width
#define MyScreenHeight [UIScreen mainScreen].bounds.size.height

@implementation MZBaseWebViewController

- (instancetype)initWithUrlString:(NSString*)urlString ;
{
    if(self = [super init])
    {
        _urlString = urlString;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self configNavigation];
    [self.view addSubview:self.webView];
    [self.view addSubview:self.progressView];
    
    [self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:self.urlString]]];

//    [self.webView makeConstraints:^(MASConstraintMaker *make) {
//        make.edges.equalTo(@0);
//    }];
    
}

-(void)configNavigation
{
    UIButton *backButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 44, 44)];
    backButton.tintColor = [UIColor blackColor];
    [backButton setImage:[UIImage imageNamed:@"icon_back"] forState:UIControlStateNormal];
    [backButton setImageEdgeInsets:UIEdgeInsetsMake(0, -20, 0, 0)];
    [backButton setTitleColor:[UIColor colorWithWhite:1 alpha:0.7] forState:UIControlStateNormal];
    WEAKSELF
    [backButton bk_addEventHandler:^(id sender) {
        if (weakSelf.webView.canGoBack) {
            [weakSelf.webView goBack];
        }else{
            [weakSelf.navigationController popViewControllerAnimated:YES];
        }
    } forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *leftBackButton = [[UIBarButtonItem alloc] initWithCustomView:backButton];
    self.navigationItem.leftBarButtonItem = leftBackButton;
}


#pragma mark - WKNavigationDelegate
-(void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation{
    WEAKSELF
    [_webView evaluateJavaScript:@"document.title" completionHandler:^(NSString *string, NSError *error) {
        weakSelf.navigationItem.title.length>0 ? 0 : (self.navigationItem.title = string);
    }];
    
    
    [self.webView evaluateJavaScript:@"document.getElementById('ctl00_title').content" completionHandler:^(NSString *string, NSError *error) {
        
    }];

}

//OC在JS调用方法做的处理
-(void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message{
    //服务器固定格式写法 window.webkit.messageHandlers.名字.postMessage(内容);
    //客户端写法 message.name isEqualToString:@"名字"]
    NSLog(@"%@",message);
}


//KVO监听进度条
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
    if ([keyPath isEqualToString:NSStringFromSelector(@selector(estimatedProgress))] && object == self.webView) {
        [self.progressView setAlpha:1.0f];
        BOOL animated = self.webView.estimatedProgress > self.progressView.progress;
        [self.progressView setProgress:self.webView.estimatedProgress animated:animated];
        
        // Once complete, fade out UIProgressView
        if(self.webView.estimatedProgress >= 1.0f) {
            [UIView animateWithDuration:0.3f delay:0.3f options:UIViewAnimationOptionCurveEaseOut animations:^{
                [self.progressView setAlpha:0.0f];
            } completion:^(BOOL finished) {
                [self.progressView setProgress:0.0f animated:NO];
            }];
        }
    }
    else {
        [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
    }
}

-(WKWebView *)webView{
    if (!_webView) {
        _webView = [[WKWebView alloc] init];
        WKWebViewConfiguration* configuration = [[NSClassFromString(@"WKWebViewConfiguration") alloc] init];
        configuration.userContentController = [NSClassFromString(@"WKUserContentController") new];
        
        WKPreferences* preferences = [NSClassFromString(@"WKPreferences") new];
        preferences.javaScriptCanOpenWindowsAutomatically = YES;
        configuration.preferences = preferences;
        
        _webView = [[WKWebView alloc] initWithFrame:CGRectMake(0, 0, MyScreenWidth, MyScreenHeight - 64) configuration:configuration];
        _webView.UIDelegate = self;
        _webView.navigationDelegate = self;
        
        _webView.backgroundColor = [UIColor clearColor];
        _webView.opaque = NO;
        
        //kvo 添加进度监控
        [_webView addObserver:self forKeyPath:NSStringFromSelector(@selector(estimatedProgress)) options:0 context:nil];
        //开启手势触摸
        _webView.allowsBackForwardNavigationGestures = YES;
        
    }
    return _webView;
}

//isNavHidden这边是做了一个是否隐藏导航栏的功能，具体下载代码一看便知。
- (UIProgressView *)progressView
{
    if (!_progressView) {
        _progressView = [[UIProgressView alloc]initWithProgressViewStyle:UIProgressViewStyleDefault];
//        if (self.navigationController.navigationBarHidden == YES) {
//            _progressView.frame = CGRectMake(0, 20, self.view.bounds.size.width, 3);
//        }else{
//            _progressView.frame = CGRectMake(0, 64, self.view.bounds.size.width, 3);
//        }
        _progressView.frame = CGRectMake(0, 0, self.view.bounds.size.width, 3);
        // 设置进度条的色彩
        [_progressView setTrackTintColor:[UIColor orangeColor]];
        _progressView.progressTintColor = [UIColor whiteColor];
    }
    return _progressView;
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
